package com.xq.shop.exception;

import enums.ResultCodes;
import exception.BusinessDataException;
import exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import utils.BaseResult;

/**
 * @author gaoxiaojin
 */
@ControllerAdvice
@Slf4j
public class BusinessExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public BaseResult<Void> qWhaleBaseException(BusinessException ex) {
        log.warn(ex.getDesc(), ex);
        BaseResult<Void> result = new BaseResult<>();
        result.setCode(ex.getCode());
        result.setMessage(ex.getDesc());
        // 返回时异常上报
        return result;
    }

    @ExceptionHandler(BusinessDataException.class)
    @ResponseBody
    public BaseResult<Object> qWhaleBaseDataException(BusinessDataException ex) {
        log.warn(ex.getDesc(), ex);
        BaseResult<Object> result = new BaseResult<>();
        result.setCode(ex.getCode());
        result.setMessage(ex.getDesc());
        result.setData(ex.getData());
        // 返回时异常上报
        return result;
    }

    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public BaseResult<Void> runtimeException(RuntimeException ex) {
        log.error(ex.getMessage(), ex);
        BaseResult<Void> result = new BaseResult<>();
        result.setCode(ResultCodes.RUNTIME_ERROR.getCode());
        // 将异常的消息也打印出来，不用固定的字符替代，方便排查
        result.setMessage(ex.getMessage());
        return result;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BaseResult<Void> exception(Exception ex) {
        log.error(ex.getMessage(), ex);
        BaseResult<Void> result = new BaseResult<>();
        result.setCode(ResultCodes.SYSTEM_ERROR.getCode());
        // 将异常的消息也打印出来，不用固定的字符替代，方便排查
        result.setMessage(ex.getMessage());
        return result;
    }

}
